import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [],
    userBalance: 1000,
    orders: []
  }),

  getters: {
    cartTotal: (state) => {
      return state.items.reduce((total, item) => total + item.price * item.quantity, 0)
    },
    cartItemCount: (state) => {
      return state.items.reduce((count, item) => count + item.quantity, 0)
    },
    canAfford: (state) => (amount) => {
      return state.userBalance >= amount
    }
  },

  actions: {
    addToCart(product) {
      const existingItem = this.items.find(item => item.id === product.id)
      
      if (existingItem) {
        existingItem.quantity += 1
      } else {
        this.items.push({
          ...product,
          quantity: 1
        })
      }
    },

    removeFromCart(productId) {
      this.items = this.items.filter(item => item.id !== productId)
    },

    updateQuantity(productId, quantity) {
      const item = this.items.find(item => item.id === productId)
      if (item) {
        if (quantity <= 0) {
          this.removeFromCart(productId)
        } else {
          item.quantity = quantity
        }
      }
    },

    clearCart() {
      this.items = []
    },

    recharge(amount) {
      if (amount > 0) {
        this.userBalance += amount
      }
    },

    purchase() {
      if (this.canAfford(this.cartTotal)) {
        this.userBalance -= this.cartTotal
        
        const order = {
          id: Date.now(),
          items: [...this.items],
          total: this.cartTotal,
          date: new Date().toISOString()
        }
        
        this.orders.unshift(order)
        this.clearCart()
        
        return { success: true, order }
      } else {
        return { success: false, message: '余额不足' }
      }
    }
  },

  persist: {
    enabled: true,
    strategies: [
      {
        key: 'cart',
        storage: localStorage
      }
    ]
  }
})